//
//  XFImagePickerPreviewController.swift
//  multi_show
//
//  Created by 李旭峰 on 2020/9/15.
//

import UIKit

class XFImagePickerPreviewController: UIViewController,UICollectionViewDelegateFlowLayout,UICollectionViewDataSource {
    weak var delegate:MTImagePickerDataSourceDelegate!
    var dataSource:[MTImagePickerModel]!
    var initialIndexPath:IndexPath?
    
    var topViews: [UIView] = []
    var bottomViews: [UIView] = []
    
    private lazy var lbIndex: UILabel = UILabel()
    private lazy var collectionView: XFImagePickerCollectionView = {
        let config = MTImagePickerFlowLayout()
        config.scrollDirection = .horizontal
        let collectionView = XFImagePickerCollectionView(frame: CGRect.zero, collectionViewLayout: config)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.isPrefetchingEnabled = true
        collectionView.isPagingEnabled = true
        return collectionView
    }()
    private lazy var btnCheck: UIButton = UIButton(type: .custom)
    private lazy var lbSelected: UILabel = UILabel()
    
    private var initialScrollDone = false

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.collectionView.backgroundColor = UIColor.white
        self.view.addSubview(self.collectionView)
        self.collectionView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview()
            make.top.bottom.equalToSuperview()
        }
        let vSaveTopView = UIView()
        vSaveTopView.backgroundColor = UIColor(hexStr: "#000000", alpha: 0.2)
        self.view.addSubview(vSaveTopView)
        vSaveTopView.snp.makeConstraints { (make) in
            make.leading.top.trailing.equalToSuperview()
            make.height.equalTo(vSafeTop)
        }
        let vHeaderView = UIView()
        vHeaderView.backgroundColor = UIColor(hexStr: "#000000", alpha: 0.2)
        self.view.addSubview(vHeaderView)
        vHeaderView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(vSaveTopView.snp.bottom)
            make.height.equalTo(44)
        }
        let btnBack = UIButton(type: .custom)
        btnBack.setTitle("Back", for: .normal)
        btnBack.setTitleColor(UIColor(hexStr: "#047AFF", alpha: 1.0), for: .normal)
        btnBack.addTarget(self, action: #selector(btnBackTouch(_:)), for: .touchUpInside)
        btnBack.titleLabel?.font = FontAsset.PingFangSC_Regular.size(14)
        vHeaderView.addSubview(btnBack)
        self.topViews.append(btnBack)
        btnBack.snp.makeConstraints { (make) in
            make.top.leading.bottom.equalToSuperview()
            make.width.equalTo(80)
        }
        self.lbIndex.font = FontAsset.PingFangSC_Semibold.size(14)
        self.lbIndex.textColor = UIColor.white
        self.lbIndex.textAlignment = .center
        vHeaderView.addSubview(self.lbIndex)
        self.topViews.append(self.lbIndex)
        self.lbIndex.snp.makeConstraints { (make) in
            make.center.equalToSuperview()
        }
        
        self.btnCheck.setImage(UIImage(named: "picture_unselect"), for: .normal)
        self.btnCheck.setImage(UIImage(named: "picture_select"), for: .selected)
        self.btnCheck.addTarget(self, action: #selector(btnCheckTouch(_:)), for: .touchUpInside)
        vHeaderView.addSubview(self.btnCheck)
        self.topViews.append(self.btnCheck)
        self.btnCheck.snp.makeConstraints { (make) in
            make.top.trailing.bottom.equalToSuperview()
            make.width.equalTo(self.btnCheck.snp.height)
        }
        let vBottomView = UIView()
        vBottomView.backgroundColor = UIColor(hexStr: "#000000", alpha: 0.2)
        self.view.addSubview(vBottomView)
        vBottomView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview()
//            make.top.equalTo(self.collectionView.snp.bottom)
            make.height.equalTo(44)
        }
        self.lbSelected.text = "0"
        self.lbSelected.textColor = UIColor(hexStr: "#FFFFFF", alpha: 1.0)
        self.lbSelected.backgroundColor = UIColor(hexStr: "#047AFF", alpha: 1.0)
        self.lbSelected.textAlignment = .center
        self.lbSelected.layer.cornerRadius = 10
        self.lbSelected.layer.masksToBounds = true
        vBottomView.addSubview(self.lbSelected)
        self.bottomViews.append(vBottomView)
        self.lbSelected.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.height.equalTo(20)
            make.width.equalTo(40)
        }
        let lbSelectedTag = UILabel()
        lbSelectedTag.text = "Selected"
        lbSelectedTag.textColor = UIColor.white
        lbSelectedTag.font = FontAsset.PingFangSC_Regular.size(12)
        vBottomView.addSubview(lbSelectedTag)
        self.bottomViews.append(lbSelectedTag)
        lbSelectedTag.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.leading.equalTo(self.lbSelected.snp.trailing).offset(8)
            make.trailing.equalToSuperview().offset(-16)
        }
        let vSaveBottomView = UIView()
        vSaveBottomView.backgroundColor = UIColor(hexStr: "#000000", alpha: 0.2)
        self.view.addSubview(vSaveBottomView)
        vSaveBottomView.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(vBottomView.snp.bottom)
            make.height.equalTo(vSafeBottom)
            make.bottom.equalToSuperview()
        }
        
        self.lbSelected.text = String(delegate.selectedSource.count)
        self.lbIndex.text = "\(initialIndexPath?.row ?? 0 + 1)/\(dataSource.count)"
        self.collectionView.register(VideoAssetPickerPreviewCell.self, forCellWithReuseIdentifier: "VideoAssetPickerPreviewCell")
        self.collectionView.register(ImagePickerPreviewCell.self, forCellWithReuseIdentifier: "ImagePickerPreviewCell")
        
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        self.navigationController?.setNavigationBarHidden(true, animated: false)
        self.scrollViewDidEndDecelerating(self.collectionView)
    }
    
    override var prefersStatusBarHidden: Bool {
        get {
            return true
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        self.navigationController?.isNavigationBarHidden = false
    }
    
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        if !self.initialScrollDone {
            self.initialScrollDone = true
            if let initialIndexPath = self.initialIndexPath {
                self.collectionView.scrollToItem(at: initialIndexPath, at: .right, animated: false)
            }
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let model = self.dataSource[indexPath.row]
        if model.mediaType == .Photo {
            let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "ImagePickerPreviewCell", for: indexPath as IndexPath) as! ImagePickerPreviewCell
            cell.layer.shouldRasterize = true
            cell.layer.rasterizationScale = UIScreen.main.scale
            cell.initWithModel(model, controller: self)
            return cell
        } else {
            let cell = self.collectionView.dequeueReusableCell(withReuseIdentifier: "VideoAssetPickerPreviewCell", for: indexPath as IndexPath) as! VideoAssetPickerPreviewCell
            cell.layer.shouldRasterize = true
            cell.layer.rasterizationScale = UIScreen.main.scale
            cell.initWithModel(model: model,controller:self)
            return cell
        }
    }
    
    // 旋转处理
    override func willRotate(to toInterfaceOrientation: UIInterfaceOrientation, duration: TimeInterval) {
        if self.interfaceOrientation.isPortrait != toInterfaceOrientation.isPortrait {
            if let videoCell = self.collectionView.visibleCells.first as? VideoPickerPreviewCell {
                // CALayer 无法autolayout 需要重设frame
                videoCell.resetLayer(frame: UIScreen.main.compatibleBounds)
            }else if let videoCell = self.collectionView.visibleCells.first as? VideoAssetPickerPreviewCell {
                videoCell.resetLayer(frame: UIScreen.main.compatibleBounds)
            }
            self.collectionView.prevItemSize = (self.collectionView.collectionViewLayout as! MTImagePickerPreviewFlowLayout).itemSize
            self.collectionView.prevOffset = self.collectionView.contentOffset.x
            self.collectionView.collectionViewLayout.invalidateLayout()
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: self.collectionView.bounds.width, height: self.collectionView.bounds.height)
    }
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        print("cell will scroll")
        let cell = self.collectionView.visibleCells.first
        if let videoCell = cell as? VideoPickerPreviewCell {
            videoCell.stopOnPlay()
        }else if let videoCell = cell as? VideoAssetPickerPreviewCell {
            videoCell.stopOnPlay()
      }
    }
    //MARK:UIScrollViewDelegate
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        if let videoCell = self.collectionView.visibleCells.first as? VideoPickerPreviewCell {
            videoCell.didScroll()
        }else if let videoCell = self.collectionView.visibleCells.first as? VideoAssetPickerPreviewCell {
            videoCell.didScroll()
        }
    }
    
    //防止visibleCells出现两个而不是一个，导致.first得到的是未显示的cell
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.perform(#selector(MTImagePickerPreviewController.didEndDecelerating), with: nil, afterDelay: 0)
    }
    
    @objc func didEndDecelerating() {
        let cell = self.collectionView.visibleCells.first
        if let videoCell = cell as? VideoPickerPreviewCell {
            videoCell.didEndScroll()
        }else if let videoCell = cell as? VideoAssetPickerPreviewCell {
          videoCell.didEndScroll()
        }else if let imageCell = cell as? ImagePickerPreviewCell {
            imageCell.didEndScroll()
        }
        if let index = self.collectionView.indexPathsForVisibleItems.first {
            self.lbIndex.text = "\(index.row + 1)/\(dataSource.count)"
            let model = self.dataSource[index.row]
            self.btnCheck.isSelected = delegate.selectedSource.contains(model)
        }
    }
    
    @IBAction func btnBackTouch(_ sender: AnyObject) {
        let _ = self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func btnCheckTouch(_ sender: UIButton) {
        if delegate.selectedSource.count < delegate.maxCount || sender.isSelected == true {
            sender.isSelected = !sender.isSelected
            if let indexPath = self.collectionView.indexPathsForVisibleItems.first {
                let model = self.dataSource[indexPath.row]
                if sender.isSelected {
                    delegate.selectedSource.append(model)
                    sender.heartbeatsAnimation(duration: 0.15)
                }else {
                    let willRemoveItem = self.dataSource[indexPath.row]
                    if delegate.selectedSource.contains(willRemoveItem) {
                        let willRemoveIndex = (delegate.selectedSource as NSArray).index(of: willRemoveItem)
                        delegate.selectedSource.remove(at: willRemoveIndex)
                    }
                }
                self.lbSelected.text = String(delegate.selectedSource.count)
                self.lbSelected.heartbeatsAnimation(duration: 0.15)
            }
        } else {
            let alertView = FlashAlertView(message: "已达到最大选择数", delegate: nil)
            alertView.show()
        }
    }
}
